package com.pfzy.utildemo.activity.record.soundrecord;

import com.pfzy.utildemo.activity.record.soundrecord.constatns.SoundRecordConstant;
import com.pfzy.utildemo.activity.record.soundrecord.db.AudioFileInfo;
import com.pfzy.utildemo.activity.record.soundrecord.db.DbManager;
import com.pfzy.utildemo.activity.record.soundrecord.helper.CheckUploadHelper;
import com.pfzy.utildemo.activity.record.soundrecord.upload.Dto.UploadAudioInfo;
import com.pfzy.utildemo.activity.record.soundrecord.upload.UpLoadManager;
import com.pfzy.utildemo.activity.record.soundrecord.upload.callback.SimpleResumeUploadCallback;
import com.pfzy.utildemo.activity.record.soundrecord.util.RecordCollectionsUtil;
import com.pfzy.lib.config.log.MyLog;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 上传检查线程
 */
public class CheckUploadRunnable implements Runnable {
    public static final long RESUME_UPLOAD_FAIL_POSITION = -98;
    public static final long RESUME_UPLOAD_SUCC_POSITION = -99;
    private static boolean mIsStart = false;
    private List<AudioFileInfo> mFileInfoList = null;
    private int logCount = 0;

    @Override
    public void run() {
        _logd("run(), mIsStart=" + mIsStart);
        if (!mIsStart) {
            mIsStart = true;
            try {
                // 查询不上传成功和开始时间小于当前时间
                this.mFileInfoList = DbManager.getInstance().queryByNotuploadSuccAndStartTimeLtCurrentAndDesc();
                StringBuilder debugSb = new StringBuilder("总体查询的结果  mFileInfoList.size=" + RecordCollectionsUtil.getSize(this.mFileInfoList));
                _logd(debugSb.toString());
                execUpload();
            } catch (Exception e) {
                _loge("检查上传过程发生 exception = " + e.toString());
            }
        }
    }

    /**
     * 执行上传
     */
    public void execUpload() {
        if (RecordCollectionsUtil.isEmpty(this.mFileInfoList)) {
            _logd("FileList为null，共执行 " + this.logCount + " 次 execUpload");
            // 删除数据库上传状态完成的组
            deleteDbUploadStatusDoneGroup();
            return;
        }

        AudioFileInfo exceAudioFileInfo = this.mFileInfoList.remove(0);
        _logd("execUpload() -> 第" + this.logCount + "次\t 正在上传信息 ," + exceAudioFileInfo);
        this.logCount++;

        // 单个音频文件信息 to 上传信息
//        UploadAudioInfo uploadAudioInfo = CheckUploadHelper.singleAuidoFileInfo2UplaodInfo(exceAudioFileInfo);
//        // 按文件路径查询并更新上传状态
//        DbManager.getInstance().queryByFilePathAndUpdateUploadStatus(exceAudioFileInfo.getAudioFilePath(), SoundRecordConstant.UploadStatus.UPLOAD_ING);
//        UpLoadManager.resumeToUpload(uploadAudioInfo, new SimpleResumeUploadCallback() {
//            @Override
//            public void onFailed(UploadAudioInfo info, int errorCode, String message) {
//                try {
//                    _logd("onFailed() -> " + errorCode + "--" + message + "\t " + info);
//                    // 按文件路径查询并更新上传状态
//                    DbManager.getInstance().queryByFilePathAndUpdateUploadStatus(info.getFilePathList().get(0), SoundRecordConstant.UploadStatus.NO_UPLOAD);
//                    execUpload();
//                } catch (Exception e) {
//                    _loge("上传 onFail流程 发生异常 -> " + e.toString());
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onCompleteSuccess(UploadAudioInfo info, List<String> successFilePathList) {
//                try {
//                    String succFilePath = successFilePathList.get(0);
//                    _logd("----->>>> onCompleteSuccess() -> " + info + "\t 路径=" + succFilePath);
//                    // 按文件路径查询并更新上传状态和指针
//                    DbManager.getInstance().queryByFilePathAndUpdateUploadStatusAndPosition(succFilePath, SoundRecordConstant.UploadStatus.UPLOAD_DONE, -99L);
//                    FileUtil.deleteFile(succFilePath);
//                    execUpload();
//                } catch (Exception e) {
//                    _loge("上传 onCompleteSuccess流程 发生异常 -> " + e.toString());
//                    e.printStackTrace();
//                }
//            }
//        });
    }

    /**
     * 删除数据库上传状态完成的组
     */
    private void deleteDbUploadStatusDoneGroup() {
        _logd("enter  deleteDbUploadStatusDoneGroup()");
        // 分组ID列表
//        Set<String> allGroupSet = DbManager.getInstance().queryGroudIdList();
//        if (!RecordCollectionsUtil.isEmpty(allGroupSet) && !RecordHelper.getInstance().isRecording()) {
//            Set<String> groupSet = new HashSet<>();
//            for (String group : allGroupSet) {
//                // 根据组ID查询未上传完成的
//                List<AudioFileInfo> tmpList = DbManager.getInstance().queryByGroupIdAndNotUploadDone(group);
//                if (RecordCollectionsUtil.isEmpty(tmpList)) {
//                    groupSet.add(group);
//                }
//            }
//            if (!RecordCollectionsUtil.isEmpty(groupSet) && !RecordHelper.getInstance().isRecording()) {
//                for (String deleteGroup : groupSet) {
//                    // 删除对应的组ID
//                    DbManager.getInstance().deleteGroup(deleteGroup);
//                }
//            }
//        }
    }

    private void _logd(String msg) {
        MyLog.logd("上传检查线程 " + msg);
    }

    private void _loge(String msg) {
        MyLog.loge("上传检查线程 " + msg);
    }
}
